using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.TableEFCore;
using MinimalistFoodStreet.BackEnd.Server.Server.RequestExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.Server.ResponseExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables 
{
	[InjectClass]
	public class ErrorLogsServer : IErrorLogsServer
	{
		private readonly ServerRepository _serverRepository;
		public ErrorLogsServer (DbContext dbContext) 
		{
			_serverRepository = new ServerRepository(dbContext);
		}
		
		public async Task<ResponseApiDto> AddAsync(RequestCreateErrorLogsDto dto)
		{
			int affectedRows=await _serverRepository.errorLogsEFCore.AddAsync(dto.ToCreateEntity());
			return ResponseApiDto.Create(affectedRows);
		}
		
		public async Task<ResponseApiDto> UpdateAsync(RequestUpdateErrorLogsDto dto)
		{
			ErrorLog errorLog = await _serverRepository.errorLogsEFCore.Query(d=>d.ElId==dto.id).SingleOrDefaultAsync();
			if(errorLog==null)
			{
				return ResponseApiDto.Fail("该实例不存在");
			}
			int affectedRows = await _serverRepository.errorLogsEFCore.UpdateAsync(errorLog);
			return ResponseApiDto.Create(affectedRows);
		}
		
		public async Task<ResponseApiDto> DeleteAsync(RequestDeleteErrorLogsDto dto)
		{
			int affectedRows = await _serverRepository.errorLogsEFCore.Query(d=>d.ElId==dto.id).ExecuteDeleteAsync();
			if(affectedRows == 0)
			{
				return ResponseApiDto.Fail("该实例不存在");
			}
			return ResponseApiDto.Create(affectedRows);
		}

		public async Task<ResponseApiDto> DetailAsync(int id)
		{
			ErrorLog errorLog = await _serverRepository.errorLogsEFCore.Query(d=>d.ElId==id).SingleOrDefaultAsync();
			if(errorLog == null)
			{
				return ResponseApiDto.Fail("该实例不存在");
			}
			return ResponseApiDto.Ok("数据已获取",errorLog.ToResponseDto());
		}
		
		public async Task<ResponseApiDto> PaginationAsync(int page,int limit,string? key)
		{
			int total = 0;
			List<ErrorLog> errorLogs = await _serverRepository.errorLogsEFCore.Pagination(d=>true,false,d=>d.ElId,out total,page,limit).ToListAsync();
			List<ResponseErrorLogsDto> responseErrorLogsDtos = errorLogs.Select(d=>d.ToResponseDto()).ToList();
			return ResponseApiDto.Ok("数据已获取",new {data=responseErrorLogsDtos,total=total});
		}
	}
}